package work.linruchang.util.bean.wrapper.db;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import lombok.Data;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;

/**
 * select的列信息
 *
 * @author LinRuChang
 * @version 1.0
 * @date 2022/01/26
 * @since 1.8
 **/
@Data
public class SqlColumnInfo implements Serializable {

    public SqlColumnInfo(TableInfo tableInfo, String columnName, Class columnType, String columnAlias, List columnValues, String sqlType) {
        this(tableInfo,columnName,columnType,columnAlias,sqlType);
        Assert.isFalse(StrUtil.equals(sqlType,SQL_TYPE_SELECT), "此构建器仅支持Where、On类型的构建，请检查");
        this.columnValues = columnValues;
    }

    public SqlColumnInfo(TableInfo tableInfo, String columnName, Class columnType, String columnAlias, String sqlType) {
        this.tableInfo = tableInfo;
        this.columnName = columnName;
        this.columnType = columnType;
        this.columnAlias = columnAlias;
    }

    /**
     * 输入时的原始SQL片段
     * 基于此字段进行解析后续的字段
     */
    String rowSqlFragment;

    /**
     * 列{columnName}所属的表
     */
    TableInfo tableInfo;

    /**
     * 列名
     */
    String columnName;

    /**
     * 列{columnName}数据类型
     */
    Class columnType;

    /**
     * 列别名
     */
    String columnAlias;

    /**
     * sql类型
     * 参考{@link SqlColumnInfo#SQL_TYPE_SELECT}
     */
    String sqlType;
    public static final String SQL_TYPE_SELECT = "SELECT";
    public static final String SQL_TYPE_WHERE = "WHERE";
    public static final String SQL_TYPE_ON = "ON";

    /**
     * 仅仅只用于WHERE类型的时候
     */
    List<Object> columnValues;

    /**
     * 别名是否是系统准备用的别名
     * @return
     */
    public boolean isSystemAlias() {
        boolean result = false;
        result = StrUtil.equals(columnAlias, StrUtil.format("{}.{}", tableInfo.getTableAlias(), columnName));
        //主表别名可空
        if (getTableInfo().getMasterTableFlag() && StrUtil.isBlank(columnAlias)) {
            result = true;
        }
        return result;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {return true;}
        if (o == null || getClass() != o.getClass()) {return false;}
        SqlColumnInfo that = (SqlColumnInfo) o;
        return Objects.equals(tableInfo, that.tableInfo) &&
                Objects.equals(columnName, that.columnName) &&
                Objects.equals(columnType, that.columnType) &&
                Objects.equals(columnAlias, that.columnAlias);
    }
    @Override
    public int hashCode() {
        return Objects.hash(tableInfo, columnName, columnType, columnAlias);
    }

    @Override
    public String toString() {
        String sqlTemplate = "{}.{}";
        if (StrUtil.isNotBlank(columnAlias)) {
            sqlTemplate = "{}.{} AS '{}'";
        }
        return StrUtil.format(sqlTemplate, tableInfo.getTableAlias(), columnName, columnAlias);
    }
}
